package com.example.qimo
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.SearchView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.BufferedReader
import java.io.InputStreamReader
import kotlin.concurrent.thread



class MainActivity : AppCompatActivity() {
    private lateinit var listView: ListView
    private lateinit var searchView: SearchView
    private lateinit var cities: List<City>
    private lateinit var displayedCities: List<City>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)

        listView = findViewById(R.id.listView)
        searchView = findViewById(R.id.searchView)

        thread {
            val str: String? = readFileFromRaw(R.raw.citycode)
            if (str.isNullOrEmpty()) {
                Log.e("MainActivity", "Failed to read city codes from file")
                return@thread
            }
            val gson = Gson()
            val CityType: java.lang.reflect.Type = object : TypeToken<List<City>>() {}.type
            cities = gson.fromJson(str, CityType)

            // 过滤掉无效的城市代码
            cities = cities.filter { it.city_code.isNotEmpty() }

            // 更新 UI 必须在主线程中进行
            runOnUiThread {
                updateListView("")
            }

            Log.d("MainActivity", "Cities: $cities")
        }

        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                query?.let { updateListView(it) }
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                newText?.let { updateListView(it) }
                return true
            }
        })

        // 设置点击监听器
        listView.setOnItemClickListener { _, _, position, _ ->
            val cityCode: String = displayedCities[position].city_code
            val intent = Intent(this, Main2Activity::class.java)
            intent.putExtra("city_code", cityCode)
            startActivity(intent)
        }
    }

    private fun updateListView(query: String) {
        displayedCities = if (query.isEmpty()) {
            cities
        } else {
            cities.filter { it.city_name.contains(query, ignoreCase = true) }
        }

        val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, displayedCities.map { it.city_name })
        listView.adapter = adapter
    }

    // 从 raw 资源文件中读取数据
    private fun readFileFromRaw(rawName: Int): String? {
        try {
            val inputReader = InputStreamReader(resources.openRawResource(rawName))
            val bufReader = BufferedReader(inputReader)
            val result = StringBuilder()
            var line: String?
            while (bufReader.readLine().also { line = it } != null) {
                result.append(line)
            }
            return result.toString()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }
}